package com.jiaquyun.jcps.utils

import androidx.lifecycle.MutableLiveData
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.jiaquyun.jcps.app.BaseApplication


class AMapLocationUtils : AMapLocationListener {

    companion object {
        @Volatile
        private var mLocationUtils: AMapLocationUtils? = null

        fun instance(): AMapLocationUtils? {
            if (mLocationUtils == null) {
                synchronized(
                    AMapLocationUtils::class.java
                ) { if (mLocationUtils == null) mLocationUtils = AMapLocationUtils() }
            }
            return mLocationUtils
        }
    }

    val locationDataLiveData = MutableLiveData<MutableMap<String, String>>()

    private var mLocationClient: AMapLocationClient? = null
    private var mLocationOption: AMapLocationClientOption? = null
    private var mLocationListener: AMapLocationListener? = null

    init {
        //初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption?.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption?.interval = 30 * 1000
        //开启缓存机制
        mLocationOption?.isLocationCacheEnable = true
        //初始化定位
        mLocationClient = AMapLocationClient(BaseApplication.INSTANCE)
        //设置定位回调监听
        mLocationClient?.setLocationListener(this)
        //设置定位参数
        mLocationClient?.setLocationOption(mLocationOption)
    }

    override fun onLocationChanged(p0: AMapLocation?) {
        p0?.let {
            val locationMaps: MutableMap<String, String> = mutableMapOf(
                "lat" to it.latitude.toString(),
                "lng" to it.longitude.toString()
            )
            locationDataLiveData.postValue(locationMaps)
        }
    }

    /**
     * 启动定位
     */
    fun startLocation() {
        mLocationClient?.startLocation()
    }

    /**
     * 停止定位
     */
    fun stopLocation() {
        mLocationClient?.stopLocation()
    }

    /**
     * 销毁定位客户端
     */
    fun onDestroy() {
        mLocationUtils = null
        mLocationClient?.onDestroy()
    }
}